package com.serverTechnology.teamsGroups.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.sys.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.sys.modular.user.entity.SysUserOrg;
import cn.stylefeng.roses.kernel.sys.modular.user.service.SysUserOrgService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.serverTechnology.resource.entity.DeviceEntity;
import com.serverTechnology.resource.entity.ManagementEntity;
import com.serverTechnology.resource.mapper.DeviceMapper;
import com.serverTechnology.resource.mapper.ManagementMapper;
import com.serverTechnology.resource.service.IManagementService;
import com.serverTechnology.teamsGroups.constants.FixedNames;
import com.serverTechnology.teamsGroups.entity.GroupUser;
import com.serverTechnology.teamsGroups.entity.dto.*;


import com.serverTechnology.teamsGroups.entity.ProDeviceToolUser;
import com.serverTechnology.teamsGroups.entity.ProModel;
import com.serverTechnology.teamsGroups.entity.SysDict;
import com.serverTechnology.teamsGroups.entity.dto.*;
import com.serverTechnology.teamsGroups.entity.vo.DeviceTreeVo;
import com.serverTechnology.teamsGroups.entity.vo.ProModelVo;
import com.serverTechnology.teamsGroups.mapper.ProDeviceToolMapper;
import com.serverTechnology.teamsGroups.mapper.ProModelMapper;
import com.serverTechnology.teamsGroups.mapper.UserMapper;
import com.serverTechnology.teamsGroups.service.IGroupUserService;
import com.serverTechnology.teamsGroups.service.ProDeviceToolUserService;
import com.serverTechnology.teamsGroups.service.ProModelService;
import com.serverTechnology.teamsGroups.entity.vo.ProModelVo;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;


@Service("ProModelServiceImpl")
public class ProModelServiceImpl extends ServiceImpl<ProModelMapper, ProModel> implements ProModelService {

    @Resource
    private ProModelMapper proModelMapper;

    @Resource
    private ProDeviceToolUserService teProDeviceToolUserService;
    @Resource
    private ProDeviceToolMapper proDeviceToolMapper;

    //管理
    @Resource
    private ManagementMapper managementMapper;

    //设备
    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private IManagementService managementService;

    @Resource
    private UserMapper userMapper;
    /**
     * 新增产线模型
     *
     * @param proModel
     */
    @Override
    public void add(ProModelAddDto proModel) {
        ProModel proModels = new ProModel();
        proModels.setSortNo(getTeachplanCount(proModel.getPid()) + 1);
        BeanUtil.copyProperties(proModel, proModels);
        try {
            this.save(proModels);
        } catch (Exception e) {
            throw new RuntimeException("编码不能重复");
        }

    }

    /**
     * 修改产线模型
     *
     * @param proModel
     */
    @Override
    public void edit(ProModelEditDto proModel) {
        ProModel proModels = new ProModel();
        BeanUtil.copyProperties(proModel, proModels);
        try {
            this.updateById(proModels);
        } catch (Exception e) {
            throw new RuntimeException("编码不能重复");
        }
    }

    /**
     * 查询产线模型详情
     *
     * @param id
     * @return
     */
    @Override
    public Object sel(Long id) {
        return this.getById(id);
    }

    /**
     * 删除产线模型
     *
     * @param id
     */
    @Override
    public void del(Long id) {
        // 获取所有 ProModel 实体列表
        List<ProModel> list = this.list();

        // 收集所有子级和当前记录
        List<ProModel> proModels = collectChildrenAndSelf(id, list);

        // 遍历
        proModels.forEach(proModel -> {
            // 删除设备工具
            if (proModel.getType().equals(FixedNames.TOW)) {
                List<ProDeviceToolUser> proDeviceToolUsers = proDeviceToolMapper.selectList(null);
                //获取要删除的数据
                List<ProDeviceToolUser> proDeviceToolUserss = collectDeviceToolUsersAndSelf(proModel.getId(), proDeviceToolUsers);
                //批量删除
                if (ObjectUtil.isNotEmpty(proDeviceToolUserss)) {
                    proDeviceToolMapper.deleteBatchIds(proDeviceToolUserss);
                }
            }
        });

        if (ObjectUtil.isNotEmpty(proModels)) {
            // 批量删除
            this.removeBatchByIds(proModels);
        }
    }

    /**
     * 分页查询
     *
     * @param proModel
     * @return
     */
    @Override
    public List<ProModelVo> pages(ProModelDto proModel) {
        List<ProModel> list = this.list(new LambdaUpdateWrapper<ProModel>()
                .like(ObjectUtil.isNotEmpty(proModel.getModelName()), ProModel::getModelName, proModel.getModelName())
                .orderBy(true, true, ProModel::getSortNo));
        // 创建 ProModelVo 列表
        List<ProModelVo> proModelVoList = new ArrayList<>();

        // 将 ProModel 转换为 ProModelVo
        for (ProModel model : list) {
            ProModelVo vo = new ProModelVo();
            // 复制属性
            BeanUtil.copyProperties(model, vo);
            // 将转换后的对象添加到列表中
            proModelVoList.add(vo);
        }
        return collectDeviceUsers(FixedNames.ZERO, proModelVoList);
    }


    /**
     * 递归收集设备工具
     * @param id
     * @param proModelVo
     * @return
     */
    private List<ProModelVo> collectDeviceUsers(Long id, List<ProModelVo> proModelVo) {
        List<ProModelVo> collect = proModelVo.stream()
                .filter(proModel -> !proModel.getType().equals(FixedNames.TOW)).collect(Collectors.toList());
        HashSet<ProModelVo> proModels = new HashSet<>();
        collect.forEach(proModel -> {
            // 判断是否是当前记录的父级
            if (proModel.getPid().equals(id)) {
                proModels.add(proModel);
                if (!proModel.getId().equals(id)) {
                    // 添加子级
                    if (ObjectUtil.isEmpty(proModel.getChildren())) {
                        proModel.setChildren(new ArrayList<>());
                    }
                    proModel.getChildren().addAll(collectDeviceUsers(proModel.getId(), proModelVo));
                }
            }
        });
        return new ArrayList<>(proModels);
    }

    /**
     * 添加设备工具
     *
     * @param proModel
     */
    @Override
    public void saves(ProDeviceToolUserAddDto proModel) {
        ArrayList<ProDeviceToolUser> proDeviceToolUsers = new ArrayList<>();
        proModel.getResourceId().forEach(proModels -> {
                    // 遍历每个 ID
                    ProDeviceToolUser proDeviceToolUsesrs = new ProDeviceToolUser();
                    proDeviceToolUsesrs.setPid(proModel.getPid());
                    // 使用三元运算符根据 num 设置相应的 ID
                    proDeviceToolUsesrs.setResourceId(proModels);
                    proDeviceToolUsesrs.setType(proModel.getType());
                    proDeviceToolUsers.add(proDeviceToolUsesrs);
                }
        );
        // 批量添加
        teProDeviceToolUserService.saveBatch(proDeviceToolUsers);
    }

    /**
     * 查询产线模型设备工具配置列表
     * @return
     */
    @Override
    public List<ProModelVo> pageDevice(ProDeviceToolUserSeleDeviceDto proModelTool) {
        // 创建 ProModelVo 列表
        List<ProModelVo> proModelVoList = new ArrayList<>();

        // 查询符合条件的 ProModel 列表
        List<ProModel> list = this.list(new LambdaUpdateWrapper<ProModel>()
                .eq(ProModel::getType, FixedNames.TOW)
                .eq(ProModel::getPid, proModelTool.getPid()));

        // 提取 ProModel 的 ID 列表
        List<Long> collect = list.stream().map(ProModel::getId).collect(Collectors.toList());

        // 查询对应的 ProDeviceToolUser 列表
        List<ProDeviceToolUser> proDeviceToolUsers = proDeviceToolMapper.selectList(
                new LambdaQueryWrapper<ProDeviceToolUser>().in(ProDeviceToolUser::getPid, collect)
        );

        // 获取 ProDeviceToolUser 中的资源ID
        List<Long> resourceId = proDeviceToolUsers.stream().map(ProDeviceToolUser::getResourceId).collect(Collectors.toList());

        // 根据资源ID获取资源信息
        List<ManagementEntity> managementEntities = managementService.craftByIds(resourceId);

        // 查询用户信息
        List<SysUser> listUser = userMapper.selectList(new LambdaUpdateWrapper<SysUser>().in(SysUser::getUserId,resourceId));


        Map<Long, SysUser> userMap = listUser.stream().collect(Collectors.toMap(SysUser::getUserId, user -> user));

        // 将 ProDeviceToolUser 按 PID 分组
        Map<Long, List<ProDeviceToolUser>> proDeviceToolUserMap = proDeviceToolUsers.stream()
                .collect(Collectors.groupingBy(ProDeviceToolUser::getPid));

        // 将 ManagementEntity 转换为 Map 以便快速查找
        Map<Long, ManagementEntity> managementEntityMap = managementEntities.stream()
                .collect(Collectors.toMap(ManagementEntity::getId, entity -> entity));

        // 将 ProModel 转换为 ProModelVo 并设置子节点
        for (ProModel model : list) {
            ProModelVo vo = new ProModelVo();
            // 复制属性
            BeanUtil.copyProperties(model, vo);

            // 获取当前 ProModel 的子节点
            List<ProDeviceToolUser> children = proDeviceToolUserMap.get(model.getId());
            if (children != null) {
                // 为每个子节点设置相应的 ManagementEntity 信息
                children.forEach(child -> {
                    vo.getChildren().addAll(extracted(child.getResourceId(), managementEntityMap));
                    vo.getChildren().addAll(getList(child.getResourceId(), userMap ));
                });
            }

            // 将转换后的对象添加到列表中
            proModelVoList.add(vo);
        }
        return proModelVoList;
    }


    /**
     * 根据资源ID提取并生成 ProModelVo 列表
     * @param resourceId
     * @param userMap
     * @return
     */
    private List<ProModelVo> getList(Long resourceId, Map<Long, SysUser> userMap) {
        List<ProModelVo> proModelVos = new ArrayList<>();
        SysUser user = userMap.get(resourceId);
        if (ObjectUtil.isNotEmpty(user)){
            ProModelVo proModelVo = new ProModelVo();
            proModelVo.setId(user.getUserId());
            proModelVo.setModelName(user.getRealName());
            proModelVo.setType(FixedNames.TOW);
            proModelVos.add(proModelVo);
        }
        return proModelVos;
    }


    /**
     * 根据资源ID提取并生成 ProModelVo 列表
     * @param resourceId 资源ID
     * @param managementEntityMap 资源信息映射
     * @return 包含对应资源信息的 ProModelVo 列表
     */
    private List<ProModelVo> extracted(Long resourceId, Map<Long, ManagementEntity> managementEntityMap) {
        List<ProModelVo> proModelVos = new ArrayList<>();
        ManagementEntity managementEntity = managementEntityMap.get(resourceId);

        // 如果资源信息存在，则创建 ProModelVo
        if (ObjectUtil.isNotEmpty(managementEntity)) {
            ProModelVo proModelVo = new ProModelVo();
            proModelVo.setId(managementEntity.getId());
            proModelVo.setModelName(managementEntity.getResourceName());
            // 根据 deviceDistinguish 设置类型
            proModelVo.setType(managementEntity.getDeviceDistinguish().equals(FixedNames.EQUIPMENT) ? FixedNames.ZERO : FixedNames.ONE);
            proModelVo.setResourceSpecification(managementEntity.getResourceSpecification());
            proModelVos.add(proModelVo);
        }

        return proModelVos;
    }


    /**
     * 递归收集产线模型所有子级和当前记录
     *
     * @param id
     * @param list
     * @return
     */
    private List<ProModel> collectChildrenAndSelf(Long id, List<ProModel> list) {
        // 用于存储需要删除的实体，并去重
        Set<ProModel> proModels = new HashSet<>();
        for (ProModel proModel : list) {
            if (proModel.getId().equals(id) || proModel.getPid().equals(id)) {
                proModels.add(proModel);
                // 递归收集子级的子级，并添加到 proModels 列表中
                if (!proModel.getId().equals(id)) {
                    proModels.addAll(collectChildrenAndSelf(proModel.getId(), list));
                }
            }
        }
        return new ArrayList<>(proModels);
    }


    /**
     * 遍历删除设备工具
     *
     * @param id
     * @param list
     * @return
     */
    private List<ProDeviceToolUser> collectDeviceToolUsersAndSelf(Long id, List<ProDeviceToolUser> list) {
        // 用于存储需要删除的实体，并去重
        Set<ProDeviceToolUser> deviceToolUsers = new HashSet<>();
        for (ProDeviceToolUser user : list) {
            if (user.getId().equals(id) || user.getPid().equals(id)) {
                deviceToolUsers.add(user);
                // 递归收集子级的子级，并添加到 deviceToolUsers 列表中
                if (!user.getId().equals(id)) {
                    deviceToolUsers.addAll(collectDeviceToolUsersAndSelf(user.getId(), list));
                }
            }
        }
        return new ArrayList<>(deviceToolUsers);
    }


    /**
     * @param parentId 父课id
     * @return int 最新排序号
     *
     * @description 获取最新的排序号
     */
    private Long getTeachplanCount(Long parentId) {
        LambdaQueryWrapper<ProModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProModel::getPid, parentId);
        Long count = proModelMapper.selectCount(queryWrapper);
        return count;
    }

    /**
     *设备类型菜单树
     *
     * @return
     */
    @Override
    public List<DeviceTreeVo> getDeviceTree() {
        LambdaQueryWrapper<ProDeviceToolUser> proDeviceToolUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        proDeviceToolUserLambdaQueryWrapper.eq(ProDeviceToolUser::getType, "0");
        proDeviceToolUserLambdaQueryWrapper.isNotNull(ProDeviceToolUser::getResourceId);
        List<ProDeviceToolUser> proDeviceToolUsers = proDeviceToolMapper.selectList(proDeviceToolUserLambdaQueryWrapper);

        // Step 1: 查询设备大类及其对应的类别名称
        MPJLambdaWrapper<DeviceEntity> wrapper = new MPJLambdaWrapper<>();
        wrapper.select(DeviceEntity::getId, DeviceEntity::getDeviceNumber, DeviceEntity::getDeviceName);
        wrapper.select(SysDict::getDictName);
        wrapper.eq(DeviceEntity::getDeviceDistinguish, "EQUIPMENT");
        wrapper.leftJoin(SysDict.class, SysDict::getDictCode, DeviceEntity::getDeviceCategory);
        List<DeviceTreeVo> deviceTreeData = deviceMapper.selectJoinList(DeviceTreeVo.class, wrapper);

        // Step 2: 查询所有设备（包含设备大类信息）
        List<DeviceEntity> deviceEntities = deviceMapper.selectList(new LambdaQueryWrapper<DeviceEntity>()
                .eq(DeviceEntity::getDeviceDistinguish, "EQUIPMENT"));

        // Step 3: 查询所有管理实体
        List<ManagementEntity> managementEntities = managementMapper.selectList(new LambdaQueryWrapper<ManagementEntity>()
                .eq(ManagementEntity::getDeviceDistinguish, "EQUIPMENT"));

        // Step 4: 使用 Map 加速查找
        Map<Long, DeviceTreeVo> deviceTreeMap = new HashMap<>();
        for (DeviceTreeVo treeVo : deviceTreeData) {
            treeVo.setDeviceTypeTreeVos(new ArrayList<>());
            // 初始值设为 false
            treeVo.setChecked(false);
            deviceTreeMap.put(treeVo.getId(), treeVo);
        }

        // Step 5: 构建设备类型树
        Map<Long, DeviceTreeVo.DeviceTypeTreeVo> deviceTypeMap = new HashMap<>();
        for (DeviceEntity deviceEntity : deviceEntities) {
            DeviceTreeVo parentTreeVo = deviceTreeMap.get(deviceEntity.getId());
            if (parentTreeVo != null) {
                DeviceTreeVo.DeviceTypeTreeVo deviceTypeTreeVo = new DeviceTreeVo.DeviceTypeTreeVo();
                deviceTypeTreeVo.setId(deviceEntity.getId());
                deviceTypeTreeVo.setCode(deviceEntity.getDeviceNumber());
                deviceTypeTreeVo.setDeviceName(deviceEntity.getDeviceName());
                // 初始值设为 false
                deviceTypeTreeVo.setChecked(false);
                deviceTypeTreeVo.setEquipmentTreeVos(new ArrayList<>());
                parentTreeVo.getDeviceTypeTreeVos().add(deviceTypeTreeVo);
                deviceTypeMap.put(deviceEntity.getId(), deviceTypeTreeVo);
            }
        }

        // Step 6: 构建设备树
        for (ManagementEntity managementEntity : managementEntities) {
            DeviceTreeVo.DeviceTypeTreeVo deviceTypeTreeVo = deviceTypeMap.get(managementEntity.getDeviceId());
            if (deviceTypeTreeVo != null) {
                DeviceTreeVo.DeviceTypeTreeVo.EquipmentTreeVo equipmentTreeVo = new DeviceTreeVo.DeviceTypeTreeVo.EquipmentTreeVo();
                equipmentTreeVo.setId(managementEntity.getId());
                equipmentTreeVo.setResourceName(managementEntity.getResourceName());
                equipmentTreeVo.setResourceNumber(managementEntity.getResourceNumber());
                equipmentTreeVo.setResourceSpecification(managementEntity.getResourceSpecification());
                // 检查是否有任何 ProDeviceToolUser 的 stationId 与管理实体的 id 匹配
                boolean isContained = proDeviceToolUsers.stream()
                        .anyMatch(proDeviceToolUser -> Objects.equals(Long.parseLong(String.valueOf(proDeviceToolUser.getResourceId())), managementEntity.getId()));

                equipmentTreeVo.setChecked(isContained);
                deviceTypeTreeVo.getEquipmentTreeVos().add(equipmentTreeVo);
            }
        }

        // Step 7: 更新第二级设备类型的 checked 状态，基于第三层的状态
        for (DeviceTreeVo deviceTreeVo : deviceTreeMap.values()) {
            for (DeviceTreeVo.DeviceTypeTreeVo deviceTypeTreeVo : deviceTreeVo.getDeviceTypeTreeVos()) {
                // 如果有任意一个设备被选中，则将设备类型标记为选中
                boolean anyChecked = deviceTypeTreeVo.getEquipmentTreeVos().stream()
                        .anyMatch(equipmentTreeVo -> equipmentTreeVo.getChecked());
                deviceTypeTreeVo.setChecked(anyChecked);
            }
        }

        // Step 8: 更新第一级设备大类的 checked 状态，基于第二层的状态
        for (DeviceTreeVo deviceTreeVo : deviceTreeMap.values()) {
            // 如果有任意一个设备类型被选中，则将设备大类标记为选中
            boolean anyChecked = deviceTreeVo.getDeviceTypeTreeVos().stream()
                    .anyMatch(deviceTypeTreeVo -> deviceTypeTreeVo.getChecked());
            deviceTreeVo.setChecked(anyChecked);
        }

        // 返回构建好的设备树
        return new ArrayList<>(deviceTreeMap.values());
    }





    @Override
    public List<DeviceTreeVo> getToolTree() {
        LambdaQueryWrapper<ProDeviceToolUser> proDeviceToolUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        proDeviceToolUserLambdaQueryWrapper.eq(ProDeviceToolUser::getType, "1");
        proDeviceToolUserLambdaQueryWrapper.isNotNull(ProDeviceToolUser::getResourceId);
        List<ProDeviceToolUser> proDeviceToolUsers = proDeviceToolMapper.selectList(proDeviceToolUserLambdaQueryWrapper);

        // Step 1: 查询设备大类及其对应的类别名称
        MPJLambdaWrapper<DeviceEntity> wrapper = new MPJLambdaWrapper<>();
        wrapper.select(DeviceEntity::getId, DeviceEntity::getDeviceNumber, DeviceEntity::getDeviceName);
        wrapper.select(SysDict::getDictName);
        wrapper.eq(DeviceEntity::getDeviceDistinguish, "TOOL");
        wrapper.leftJoin(SysDict.class, SysDict::getDictCode, DeviceEntity::getDeviceCategory);
        List<DeviceTreeVo> deviceTreeData = deviceMapper.selectJoinList(DeviceTreeVo.class, wrapper);

        // Step 2: 查询所有设备（包含设备大类信息）
        List<DeviceEntity> deviceEntities = deviceMapper.selectList(new LambdaQueryWrapper<DeviceEntity>()
                .eq(DeviceEntity::getDeviceDistinguish, "TOOL"));

        // Step 3: 查询所有管理实体
        List<ManagementEntity> managementEntities = managementMapper.selectList(new LambdaQueryWrapper<ManagementEntity>()
                .eq(ManagementEntity::getDeviceDistinguish, "TOOL"));

        // Step 4: 使用 Map 加速查找
        Map<Long, DeviceTreeVo> deviceTreeMap = new HashMap<>();
        for (DeviceTreeVo treeVo : deviceTreeData) {
            treeVo.setDeviceTypeTreeVos(new ArrayList<>());
            treeVo.setChecked(false); // 初始值设为 false
            deviceTreeMap.put(treeVo.getId(), treeVo);
        }

        // Step 5: 构建设备类型树
        Map<Long, DeviceTreeVo.DeviceTypeTreeVo> deviceTypeMap = new HashMap<>();
        for (DeviceEntity deviceEntity : deviceEntities) {
            DeviceTreeVo parentTreeVo = deviceTreeMap.get(deviceEntity.getId());
            if (parentTreeVo != null) {
                DeviceTreeVo.DeviceTypeTreeVo deviceTypeTreeVo = new DeviceTreeVo.DeviceTypeTreeVo();
                deviceTypeTreeVo.setId(deviceEntity.getId());
                deviceTypeTreeVo.setCode(deviceEntity.getDeviceNumber());
                deviceTypeTreeVo.setDeviceName(deviceEntity.getDeviceName());
                deviceTypeTreeVo.setChecked(false); // 初始值设为 false
                deviceTypeTreeVo.setEquipmentTreeVos(new ArrayList<>());
                parentTreeVo.getDeviceTypeTreeVos().add(deviceTypeTreeVo);
                deviceTypeMap.put(deviceEntity.getId(), deviceTypeTreeVo);
            }
        }

        // Step 6: 构建设备树
        for (ManagementEntity managementEntity : managementEntities) {
            DeviceTreeVo.DeviceTypeTreeVo deviceTypeTreeVo = deviceTypeMap.get(managementEntity.getDeviceId());
            if (deviceTypeTreeVo != null) {
                DeviceTreeVo.DeviceTypeTreeVo.EquipmentTreeVo equipmentTreeVo = new DeviceTreeVo.DeviceTypeTreeVo.EquipmentTreeVo();
                equipmentTreeVo.setId(managementEntity.getId());
                equipmentTreeVo.setResourceName(managementEntity.getResourceName());
                equipmentTreeVo.setResourceNumber(managementEntity.getResourceNumber());
                equipmentTreeVo.setResourceSpecification(managementEntity.getResourceSpecification());
                // 检查是否有任何 ProDeviceToolUser 的 stationId 与管理实体的 id 匹配
                boolean isContained = proDeviceToolUsers.stream()
                        .anyMatch(proDeviceToolUser -> Objects.equals(Long.parseLong(String.valueOf(proDeviceToolUser.getResourceId())),managementEntity.getId()));
                equipmentTreeVo.setChecked(isContained);
                deviceTypeTreeVo.getEquipmentTreeVos().add(equipmentTreeVo);
            }
        }

        // Step 7: 更新第二级设备类型的 checked 状态，基于第三层的状态
        for (DeviceTreeVo deviceTreeVo : deviceTreeMap.values()) {
            for (DeviceTreeVo.DeviceTypeTreeVo deviceTypeTreeVo : deviceTreeVo.getDeviceTypeTreeVos()) {
                // 如果有任意一个设备被选中，则将设备类型标记为选中
                boolean anyChecked = deviceTypeTreeVo.getEquipmentTreeVos().stream()
                        .anyMatch(equipmentTreeVo -> equipmentTreeVo.getChecked());
                deviceTypeTreeVo.setChecked(anyChecked);
            }
        }

        // Step 8: 更新第一级设备大类的 checked 状态，基于第二层的状态
        for (DeviceTreeVo deviceTreeVo : deviceTreeMap.values()) {
            // 如果有任意一个设备类型被选中，则将设备大类标记为选中
            boolean anyChecked = deviceTreeVo.getDeviceTypeTreeVos().stream()
                    .anyMatch(deviceTypeTreeVo -> deviceTypeTreeVo.getChecked());
            deviceTreeVo.setChecked(anyChecked);
        }

        // 返回构建好的设备树
        return new ArrayList<>(deviceTreeMap.values());

    }


}
